import { NextResponse } from 'next/server'
import { getProducts, getProductsCount, createProduct } from '@/lib/database'
import { validateSearchParams, validateProductForm, sanitizeProductData } from '@/lib/validation'
import { uploadFile } from '@/lib/storage'
import { extractUserIdFromRequest } from '@/lib/rls-middleware'

/**
 * GET /api/products - 获取产品列表
 * 支持需求 1.1, 2.1, 2.2
 */
export async function GET(request) {
    console.log(`[${new Date().toISOString()}] GET /api/products called`)
    try {
        const { searchParams } = new URL(request.url)

        // 提取并验证查询参数
        const rawParams = {
            search: searchParams.get('search'),
            type: searchParams.get('type'),
            page: searchParams.get('page'),
            limit: searchParams.get('limit'),
            userId: searchParams.get('userId')
        }

        const validatedParams = validateSearchParams(rawParams)

        // 从请求中提取用户ID（用于RLS）
        const userId = extractUserIdFromRequest(request)

        // 获取产品列表和总数
        const [products, totalCount] = await Promise.all([
            getProducts(validatedParams, userId),
            getProductsCount(validatedParams, userId)
        ])

        // 计算分页信息
        const totalPages = Math.ceil(totalCount / validatedParams.limit)
        const hasNextPage = validatedParams.page < totalPages
        const hasPrevPage = validatedParams.page > 1

        return NextResponse.json({
            success: true,
            data: {
                products,
                pagination: {
                    currentPage: validatedParams.page,
                    totalPages,
                    totalCount,
                    limit: validatedParams.limit,
                    hasNextPage,
                    hasPrevPage
                },
                filters: {
                    search: validatedParams.search || null,
                    type: validatedParams.type
                }
            }
        })

    } catch (error) {
        console.error('获取产品列表失败:', error)

        return NextResponse.json({
            success: false,
            error: {
                code: 'FETCH_PRODUCTS_FAILED',
                message: '获取产品列表失败',
                details: process.env.NODE_ENV === 'development' ? error.message : undefined
            }
        }, { status: 500 })
    }
}

/**
 * POST /api/products - 创建新产品
 * 支持需求 3.3, 3.4, 3.5, 3.6
 */
export async function POST(request) {
    try {
        const contentType = request.headers.get('content-type')
        let body

        // 处理不同的内容类型
        if (contentType?.includes('application/json')) {
            body = await request.json()
        } else if (contentType?.includes('multipart/form-data')) {
            // 处理包含文件上传的表单数据
            const formData = await request.formData()
            body = {}

            // 提取表单字段
            for (const [key, value] of formData.entries()) {
                if (key !== 'file' && key !== 'thumbnail') {
                    body[key] = value
                }
            }

            // 确保userId被正确提取
            console.log('FormData中的userId:', body.userId)

            // 处理文件字段
            const file = formData.get('file')
            const thumbnail = formData.get('thumbnail')

            if (file && file instanceof File) {
                body.file = file
            }
            if (thumbnail && thumbnail instanceof File) {
                body.thumbnail = thumbnail
            }
        } else {
            return NextResponse.json({
                success: false,
                error: {
                    code: 'INVALID_CONTENT_TYPE',
                    message: '不支持的内容类型'
                }
            }, { status: 400 })
        }

        // 验证请求数据
        const validation = validateProductForm(body)
        if (!validation.isValid) {
            return NextResponse.json({
                success: false,
                error: {
                    code: 'VALIDATION_ERROR',
                    message: '数据验证失败',
                    details: validation.errors
                }
            }, { status: 400 })
        }

        // 清理和格式化数据
        const productData = sanitizeProductData(body)

        // 处理文件上传
        if (body.file && body.file instanceof File) {
            const uploadResult = await uploadFile(body.file, 'apps')
            if (uploadResult.error) {
                return NextResponse.json({
                    success: false,
                    error: {
                        code: 'UPLOAD_FAILED',
                        message: uploadResult.error
                    }
                }, { status: 500 })
            }
            productData.file_path = uploadResult.path
            productData.url = uploadResult.url // 本地文件的访问 URL
        }

        // 处理缩略图上传
        if (body.thumbnail && body.thumbnail instanceof File) {
            const uploadResult = await uploadFile(body.thumbnail, 'thumbnails')
            if (uploadResult.error) {
                return NextResponse.json({
                    success: false,
                    error: {
                        code: 'UPLOAD_FAILED',
                        message: uploadResult.error
                    }
                }, { status: 500 })
            }
            productData.thumbnail_url = uploadResult.url
        }

        // 对于应用类型，确保有文件路径或URL
        if (productData.type === 'app') {
            if (!productData.file_path && !productData.url) {
                return NextResponse.json({
                    success: false,
                    error: {
                        code: 'VALIDATION_ERROR',
                        message: '应用类型产品必须提供文件路径或下载链接'
                    }
                }, { status: 400 })
            }
        }

        // 对于网站类型，确保有URL
        if (productData.type === 'website' && !productData.url) {
            return NextResponse.json({
                success: false,
                error: {
                    code: 'VALIDATION_ERROR',
                    message: '网站类型产品必须提供访问链接'
                }
            }, { status: 400 })
        }

        // 从请求中提取用户ID（用于RLS）
        const userId = extractUserIdFromRequest(request)

        // 创建产品
        const newProduct = await createProduct(productData, userId)

        return NextResponse.json({
            success: true,
            data: {
                product: newProduct,
                message: '产品创建成功'
            }
        }, { status: 201 })

    } catch (error) {
        console.error('创建产品失败:', error)

        // 处理特定的数据库错误
        if (error.message.includes('duplicate key')) {
            return NextResponse.json({
                success: false,
                error: {
                    code: 'DUPLICATE_PRODUCT',
                    message: '产品已存在'
                }
            }, { status: 409 })
        }

        if (error.message.includes('violates check constraint')) {
            return NextResponse.json({
                success: false,
                error: {
                    code: 'INVALID_PRODUCT_TYPE',
                    message: '无效的产品类型'
                }
            }, { status: 400 })
        }

        return NextResponse.json({
            success: false,
            error: {
                code: 'CREATE_PRODUCT_FAILED',
                message: '创建产品失败',
                details: process.env.NODE_ENV === 'development' ? error.message : undefined
            }
        }, { status: 500 })
    }
}